package com.gk.study.controller;

import com.alibaba.druid.util.StringUtils;
import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.Guest;
import com.gk.study.entity.User;
import com.gk.study.service.GuestService;
import com.gk.study.utils.AliyunOssUtil;
import com.gk.study.utils.JwtUtil;
import com.gk.study.utils.PasswordUtil;
import com.gk.study.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.RandomUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/guest")
@CrossOrigin
public class GuestController {

    @Autowired
    private GuestService guestService;

    /**
     * 查询住户信息
     *
     * @param keyword
     * @return
     */
    @GetMapping(value = "/list")
    public APIResponse list(String keyword) {
        log.info("开始查询住户信息,参数为{}", keyword);
        List<Guest> list = guestService.getGuestList(keyword);
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }


    /**
     * 新增操作
     *
     * @param guest
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/create")
    @Transactional
    public APIResponse create(Guest guest) throws IOException {
        String password = guest.getPassword();
        if (!StringUtils.isEmpty(guest.getPhone()) || !StringUtils.isEmpty(password)) {
            // 查重
            if(guestService.getGuestByPhone(guest.getPhone()) != null) {
                return new APIResponse(ResponeCode.FAIL, "号码重复");
            }
            // 加密密码
            guest.setPassword(PasswordUtil.encryptPassword(password));
            // 设置创建时间格式为 年月日小时分钟秒
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            guest.setEnterTime(LocalDateTime.now().format(formatter));
//            guest.setEnterTime(LocalDateTime.now());
            guest.setName("guest_"+RandomUtil.randomNumbers(4));
            guest.setSex("男");
            guestService.createGuest(guest);
            return new APIResponse(ResponeCode.SUCCESS, "创建成功");
        }
        return new APIResponse(ResponeCode.FAIL, "创建失败");
    }
    /**
     * 更新信息操作
     * @param guest
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/update")
    public APIResponse update(Guest guest) throws IOException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        guest.setEnterTime(LocalDateTime.now().format(formatter));
        log.info("新增住户信息，参数为{}",guest);
        guestService.updateGuest(guest);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

    /**
     * 删除用户信息操作
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(String ids){
        log.info("删除用户ids==={}", ids);
        // 批量删除
        String[] arr = ids.split(",");
        for (String id : arr) {
            guestService.deleteUser(id);
        }
        return new APIResponse(ResponeCode.SUCCESS, "删除成功");
    }
@PostMapping("/login")
public APIResponse login(Guest guest) {
    Guest responseGuest = guestService.getGuestByPhone(guest.getPhone());
    System.out.println(responseGuest);
    if(responseGuest != null) {
        // 检查密码
        if (PasswordUtil.checkPassword(guest.getPassword().toString(), responseGuest.getPassword().toString())) {
            // 密码验证成功
            ThreadLocalUtil.set(guest.getName());
            return new APIResponse(ResponeCode.SUCCESS, "查询成功", responseGuest);
        } else {
            // 密码验证失败
            return new APIResponse(ResponeCode.FAIL, "用户名或密码错误123");
        }
    } else {
        // 用户名不存在
        return new APIResponse(ResponeCode.FAIL, "用户名不存在");
    }
}
  @GetMapping("/detail")
    public APIResponse detail(@RequestParam("userId") String id){
      int i = Integer.parseInt(id);
      Guest guest =  guestService.getGuestDetail(i);
       return new APIResponse<>(ResponeCode.SUCCESS,guest);
  }
//    @RequestMapping(value = "/updateguestInfo", method = RequestMethod.POST)
//    @Transactional
//    public APIResponse updateUserInfo(Guest guest) throws IOException {
//        guestService.updateGuestPartial(guest);
//        System.out.println(guest);
//        return new APIResponse<>(ResponeCode.SUCCESS, "更新成功");
//    }
@RequestMapping(value = "/updateguestInfo", method = RequestMethod.POST)
@Transactional
public APIResponse updateUserInfo(Guest guest) throws Exception {
    String file = saveAvatar(guest);
    if(!StringUtils.isEmpty(file)) {
        guest.setAvatar(file);
        guestService.updateGuestPartial(guest);
    }
    System.out.println(guest);
    return new APIResponse<>(ResponeCode.SUCCESS, "更新成功");
}
    public String saveAvatar(Guest guest) throws IOException {
        MultipartFile file = guest.getAvatarFile();
        String fileUrl = null;

        if (file != null && !file.isEmpty()) {
            try {
                // 获取原始文件名
                String originalFilename = file.getOriginalFilename();
                // 生成唯一的文件名，确保不覆盖
                String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                // 调用阿里云 OSS 的上传方法，上传文件并获取文件的访问URL
                fileUrl = AliyunOssUtil.upLoad(filename, file.getInputStream());

                // 更新用户的头像信息为文件的访问URL
                guest.setAvatar(fileUrl);
            } catch (Exception e) {
                e.printStackTrace();
                throw new IOException("Failed to upload avatar", e);
            }
        }
        return fileUrl;
    }
    @PostMapping("/sendCode")
    public APIResponse sendVerificationCode(@RequestParam String phone) {
        guestService.sendCode(phone);
        return new APIResponse<>(ResponeCode.SUCCESS, "验证码发送成功");
    }
    @PostMapping("/verifyCode")
    public APIResponse verifyCode(@RequestParam String phone, @RequestParam String code) {
        String isVerified = guestService.verifyCode(phone, code);
            return new APIResponse<>(ResponeCode.SUCCESS, "验证码验证成功");
    }
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    @Transactional
    public APIResponse updatePwd(int userId, int password, String newPassword) throws IOException {
        Guest guest =  guestService.getGuestDetail(userId);
            if(guest.getPassword().equals(password)){
                guest.setPassword(newPassword);
                guestService.updateGuest(guest);
                System.out.println(guest.getId());
                System.out.println(guest.getPassword());
            }else {
                return new APIResponse(ResponeCode.FAIL, "原密码错误");
            }
            return new APIResponse(ResponeCode.SUCCESS, "更新成功");
        }
}
